package com.cookie.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @author xiaozzk
 */
@RestController
@RequestMapping("/session")
@Api("操作Session")
public class SessionController {
    protected HttpServletRequest request;
    protected HttpServletResponse response;

    @ApiOperation("put Session")
    @PostMapping("/add")
    public Object servletSAdd(@ApiParam(value = "名字", required = true) @RequestParam("name") String name,
                              @ApiParam(value = "值", required = true) @RequestParam("value") String value) {
        try {
            HttpSession session = request.getSession();
            session.setAttribute(name, value);
            return new MySession().setSessionName(name)
                .setSessionValue(value);
        } catch (Exception e) {
            return e;
        }
    }

    @ApiOperation("list Session")
    @GetMapping("/list")
    public Object servletSList() {
        HttpSession session = request.getSession();
        Enumeration<String> names = session.getAttributeNames();
        List<MySession> sessions = new ArrayList<>();
        while (names.hasMoreElements()) {
            String sessionName = names.nextElement();
            Object attribute = session.getAttribute(sessionName);
            sessions.add(new MySession().setSessionName(sessionName)
                .setSessionValue(attribute));
        }
        return sessions;
    }


    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
    }

    @Data
    @Accessors(chain = true)
    private static class MySession {
        private String sessionName;
        private Object sessionValue;
    }
}
